package com.henu.art.controller;

import com.henu.art.annotation.IgnoreToken;
import com.henu.art.service.AuthService;
import com.henu.art.service.Imlp.CustomRedis;
import com.henu.art.service.Imlp.UserOnlineServiceImpl;
import com.henu.art.service.UserService;
import com.henu.art.util.JWTUtil;
import com.henu.art.util.Result;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: zoey
 * \\_/__/
 * @Date: 2025/04/24/19:25
 * @Description:
 */
@RestController
@Slf4j
@RequestMapping("/auth")
@Tag(name = "授权管理", description = "授权和认证相关的操作接口")
public class AuthController {
    @Resource
    private AuthService authService;
    @Resource
    private UserOnlineServiceImpl userOnlineService;
    @Resource
    private UserService userService;
    @Resource
    private CustomRedis customRedis;

    @PostMapping("login")
    @IgnoreToken
    public Result<?> login(@RequestParam String username, @RequestParam String password) throws Exception {
        if (!username.equals(customRedis.getAdminUsername()) && userService.getById(username) == null) {
            return Result.error("用户不存在,请联系管理员");
        }
        boolean success = authService.login(username, password);
        if (success) {
            userOnlineService.setLogoutStatus(username);
            userOnlineService.setLoginStatus(username);
            return Result.ok(JWTUtil.sign(username));
        }
        return Result.error("用户名或密码错误");
    }

    @GetMapping("healthy")
    public Result<?> healthy(@RequestHeader("token") String token) {
        if (token.equals(userOnlineService.getLoginStatus(authService.getUsernameByToken(token)))) {
            return Result.ok("登陆状态正常");
            //其实也可以在这里加上刷新机制
        }
        return Result.error("账号在其他设备登录");
    }


}

